<template>
  <a-spin :spinning="loading">
    <section class="flex items-center justify-between">
      <section class="flex items-center">
        <span>服务商名称：</span>
        <a-input
          class="w-300"
          :max-length="100"
          placeholder="请输入服务商名称"
          allow-clear
          v-model="searchInp"
          @keyup.enter="search"/>
<!--        <a-select-->
<!--          allow-clear-->
<!--          class="w-200 ml-8"-->
<!--          v-model="channelId"-->
<!--          placeholder="请选择渠道"-->
<!--          @change="getData">-->
<!--          <a-select-option v-for="item in channelData" :key="item.id">{{ item.name }}</a-select-option>-->
<!--        </a-select>-->
        <a-button class="mx-8" type="primary" @click="search">搜索</a-button>
        <a-button @click="reset">重置</a-button>
      </section>
      <a-button type="primary"  icon="plus" @click="getShow()">新建</a-button>
    </section>
    <a-alert class="my-16" message="按服务商调价，同一个价格只能有至多不超过一种调价方式，调价幅度正负皆可" type="info" show-icon />
    <a-table
      row-key="id"
      :columns="columns"
      :data-source="data"
      :pagination="pagination"
    >
      <template #rangeText="rangeText, data">
        <a-tooltip :title="rangeText">
          <section>{{ rangeText }}</section>
        </a-tooltip>
      </template>
      <template #isEnable="isEnable, data">
        <a-switch v-if="$permissionJudge('PriceConfigEdit')" :checked="isEnable" @change="toggleEnable(data)"/>
      </template>
      <template #action="val, data, index">
        <a v-if="$permissionJudge('PriceConfigEdit')" href="javascript:;" @click.stop="editVendor(data)">编辑</a>
        <a-divider v-if="$permissionJudge('PriceConfigEdit') && $permissionJudge('PriceConfigDelete')" type="vertical"/>
        <a style="color: red;" href="javascript:;" v-if="$permissionJudge('PriceConfigDelete')" @click="deleteChannel(data, index)">删除</a>
      </template>
    </a-table>
    <a-modal
      v-model="showModal"
      width="660px"
      :title="`${isEdit ? '修改' : '新建'}服务商调价信息`"
      :confirm-loading="loading"
      @ok="confirm"
    >
      <a-form :form="form" class="inline-form">
        <a-row :gutter="24">
          <a-col :span="24">
            <a-form-item class="flex" label="调价渠道">
              <!-- <a-select
                class="w-full"
                placeholder="请选择调价渠道"
                disabled
                v-decorator="[
                  'channelId',
                  {rules: [{required: true, message: '请选择调价渠道'}], initialValue: channelId}
                ]"
              >
                <a-select-option v-for="item in channelData" :key="item.id" :value="item.id">{{ item.name }}</a-select-option>
              </a-select> -->
			  <sourceChannel ref="channes" placeholder="请选择调价渠道"
			           v-model="channelId" isShow="true"
			           :options="{ allowClear: true }"
			            class="flex-1 overflow-hidden" />
            <!--  <a-input type="hidden" v-decorator="['id']"/> -->
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item class="flex" label="服务商">
             <!-- <a-select
                class="w-full"
                placeholder="请选择服务商"
                v-decorator="[
                  'vendorId',
                  {rules: [{required: true, message: '请选择服务商'}]}
                ]"
              >
                <a-select-option v-for="item in vendorList" :key="item.id" :value="item.id">{{ item.name }}</a-select-option>
              </a-select> -->
			  <newVendor  ref="vendor" placeholder="请选择服务商"
			           v-model="vendorId"
			           :options="{ allowClear: true }"
			           class="flex-1 overflow-hidden"/>
            <!--  <a-input type="hidden" v-decorator="['id']"/> -->
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="调价比例(%)">
              <a-input-number
                class="w-full"
                placeholder="输入5，例如5%"
                :min="-100"
                :max="999999999"
                :precision="0"
                v-decorator="[
                  'percentage',
                  {rules: [{required: true, message: '请选择调价比例'}]}
                ]"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="调价金额(元)">
              <a-input-number
                class="w-full"
                :precision="0"
                :min="-999999999"
                :max="999999999"
                placeholder="输入5，代表5元或者5%"
                v-decorator="[
                  'price',
                  {rules: [{message: '请输入调价金额', required: true}]}
                ]"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="是否启用">
              <a-switch v-decorator="['isEnable', { valuePropName: 'checked' }]"/>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>
  </a-spin>

		
</template>
<script>
import {getAllVendors} from '@/api/vendor'
import sourceChannel from '@/components/sourceChannel'
import {tableMixins} from '@/utils/mixins'
import newVendor from '@/components/vendor/vendor'
import {
  getVendorPagedList,
  addVendorInfo,
  editVendorInfo,
  deleteVendorInfo,
  editIsEnable
} from '@/api/modifyPrice'
export default {
  name: 'ByVendor',
  	components: {sourceChannel,newVendor},
  mixins: [tableMixins],
  props: {
    channelId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      loading: false,
      enableLoading: false,
      showModal: false,
      isEdit: false,
      searchInp: '',
      form: this.$form.createForm(this),
      channelData: [],
      vendorList: [],
      columns: [
        {title: '服务商', dataIndex: 'vendorName'},
        {title: '调价幅度', dataIndex: 'rangeText', width: 400, ellipsis: true, scopedSlots: {customRender: 'rangeText'}},
        {title: '是否启用', dataIndex: 'isEnable', scopedSlots: {customRender: 'isEnable'}},
        {title: '操作', dataIndex: 'action', width: 120, scopedSlots: {customRender: 'action'}}
      ],
      data: []
    }
  },
  watch: {
    showModal(val) {
      if (val) {
        this.getChannelData()
        this.getVendorList()
      } else {
        this.isEdit = false
        this.form.resetFields()
      }
    }
  },
  created() {
    this.$watch('channelId', val => {
      val && this.search()
    }, {immediate: true})
    this.getChannelData()
  },
  methods: {
    getData() {
      this.loading = true
      getVendorPagedList({
        pageNo: this.pageNum,
        pageSize: this.rowsNum,
        channelId: this.channelId,
        vendorName: this.searchInp.trim()
      }).then(data => {
        data.items.forEach(item => {
          item.rangeText = `比例调整，${item.percentage}%， 金额调整，${item.price}元`
        })
        this.data = data.items
        this.total = data.rowCount
      }).finally(() => this.loading = false)
    },
    search() {
      this.getData()
    },
    reset() {
      this.searchInp = ''
      this.search()
    },
    editVendor(data) {
      this.isEdit = true
      this.showModal = true
      this.$nextTick(() => {
		  this.$refs.channes.getId()
		  this.$refs.vendor.getId()
        this.form.setFieldsValue(data)
      })
    },
	getShow(){
	 this.showModal = true
			
	this.$nextTick(() => {
		this.$refs.channes.getId()
       	this.$refs.vendor.getId()
	})
		 
	},
    confirm() {
      this.form.validateFields((err, values) => {
        if (!err) {
          const confirmFn = this.isEdit ? editVendorInfo : addVendorInfo
          this.loading = true
		 
		  values.channelId=this.channelId
		    values.vendorId=this.vendorId
			 console.log(values,'xxxxx')
		  // return
          confirmFn(this.$utils.trimValue(values)).then(() => {
            this.$message.success(`${this.isEdit ? '修改' : '新增'}成功！`)
            this.showModal = false
            this.getData()
          }).finally(() => this.loading = false)
        }
      })
    },
    toggleEnable(data) {
      const isEnable = !data.isEnable
      if (this.enableLoading) return
      this.enableLoading = true
      editIsEnable({ id: data.id, isEnable }).then(() => {
        data.isEnable = isEnable
      }).finally(() => this.enableLoading = false)
    },
    deleteChannel(data, index) {
      this.$confirm({
        title: '提示',
        content: '请确认是否删除当前调价信息？',
        okText: '确定',
        okType: 'danger',
        cancelText: '取消',
        onOk: () => {
          this.loading = true
          deleteVendorInfo({ id: data.id }).then(() => {
            this.$message.success('删除成功！')
            this.data.splice(index, 1)
            if (this.data.length === 0 && this.pageNum > 1) this.pageNum--
            this.getData()
          }).finally(() => this.loading = false)
        }
      })
    },
    getChannelData() {
      // this.$utils.getChannel().then(data => {
      //   this.channelData = data
      // })
    },
    getVendorList() {
      // getAllVendors().then(data => this.vendorList = data)
    }
  }
}
</script>
<style lang="less" scoped>

  /deep/ .ant-form-item-label {
    width: 100px;
    text-align: right;
  }
</style>
